package exchange.fulltest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;

import javax.security.auth.login.LoginException;

public class NetClient implements Runnable {

	private Socket requestSocket;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private String name;
	private String order;
	private int iterations;

	NetClient(String name, String order, int iterations) {
		this.name = name;
		this.order = order;
		this.iterations = iterations;
	}

	@Override
	public void run() {

		try {
			requestSocket = new Socket("localhost", 5555);
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());

			sendMessage("LOGIN;" + name + ";");
			String answer = (String) in.readObject();
			System.out.println("server>" + answer);

			if (!answer.equals("LOGINSUCCESS")) {
				System.out.println(answer);
				throw new LoginException("Login error");
			}

			Executors.newSingleThreadExecutor().execute(
					new NetClientSocketReader(in));

			for (int i = 1; i <= iterations; i++) {
				String msg = ("ORDER;" + i + ";" + order + ";" + i + ";");
				sendMessage(msg);
				System.out.println("msg " + i + " sent");
			}

			System.out.println("client>All orders are sent");

			Thread.sleep(1000);
		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (ConnectException conExc) {
			System.out.println(conExc.getMessage());
		} catch (NullPointerException nullExc) {
			System.out.println(nullExc.getMessage());
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (LoginException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			} catch (NullPointerException nullExc) {
				System.out.println(nullExc.getMessage());
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

}
